<?php
declare(strict_types=1);

namespace app\controller\admin;

use app\BaseController;
use app\model\{Admin, Role};
use think\facade\{Db, Log};
use think\Request;

class AdminController extends BaseController
{
    /**
     * 获取管理员列表
     */
    public function list(Request $request)
    {
        $where = [];
        
        // 状态筛选
        if ($status = $request->param('status')) {
            $where[] = ['status', '=', $status];
        }
        
        // 角色筛选
        if ($roleId = $request->param('role_id')) {
            $where[] = ['role_id', '=', $roleId];
        }
        
        // 关键词搜索
        if ($keyword = $request->param('keyword')) {
            $where[] = ['username|real_name', 'like', "%{$keyword}%"];
        }
        
        $list = Admin::with(['role'])
            ->where($where)
            ->field('id, username, real_name, role_id, mobile, email, status, last_login_time, create_time')
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $request->param('limit', 15),
                'page' => $request->param('page', 1)
            ]);
            
        return $this->success('获取成功', $list);
    }
    
    /**
     * 添加管理员
     */
    public function add(Request $request)
    {
        $data = $this->validate($request->post(), [
            'username' => 'require|alphaNum|length:4,20',
            'password' => 'require|length:6,20',
            'real_name' => 'require|max:20',
            'role_id' => 'require|integer',
            'mobile' => 'mobile',
            'email' => 'email'
        ]);
        
        Db::startTrans();
        try {
            // 检查用户名是否存在
            if (Admin::where('username', $data['username'])->find()) {
                throw new \Exception('用户名已存在');
            }
            
            // 检查角色是否存在
            if (!Role::find($data['role_id'])) {
                throw new \Exception('角色不存在');
            }
            
            // 创建管理员
            $admin = Admin::create([
                'username' => $data['username'],
                'password' => password_hash($data['password'], PASSWORD_DEFAULT),
                'real_name' => $data['real_name'],
                'role_id' => $data['role_id'],
                'mobile' => $data['mobile'] ?? '',
                'email' => $data['email'] ?? '',
                'status' => 1,
                'create_time' => date('Y-m-d H:i:s')
            ]);
            
            // 记录操作日志
            $this->recordOperationLog('新增', '创建管理员：' . $data['username']);
            
            Db::commit();
            return $this->success('创建成功', $admin);
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('创建管理员失败: ' . $e->getMessage());
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 更新管理员
     */
    public function edit(Request $request, $id)
    {
        $data = $this->validate($request->post(), [
            'real_name' => 'require|max:20',
            'role_id' => 'require|integer',
            'mobile' => 'mobile',
            'email' => 'email',
            'status' => 'require|in:0,1',
            'password' => 'length:6,20' // 可选
        ]);
        
        Db::startTrans();
        try {
            $admin = Admin::find($id);
            if (!$admin) {
                throw new \Exception('管理员不存在');
            }
            
            // 检查角色是否存在
            if (!Role::find($data['role_id'])) {
                throw new \Exception('角色不存在');
            }
            
            // 更新数据
            $updateData = [
                'real_name' => $data['real_name'],
                'role_id' => $data['role_id'],
                'mobile' => $data['mobile'] ?? '',
                'email' => $data['email'] ?? '',
                'status' => $data['status'],
                'update_time' => date('Y-m-d H:i:s')
            ];
            
            // 如果修改密码
            if (!empty($data['password'])) {
                $updateData['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
            }
            
            $admin->save($updateData);
            
            // 记录操作日志
            $this->recordOperationLog('修改', '更新管理员：' . $admin->username);
            
            Db::commit();
            return $this->success('更新成功');
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('更新管理员失败: ' . $e->getMessage());
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 删除管理员
     */
    public function delete(Request $request, $id)
    {
        Db::startTrans();
        try {
            $admin = Admin::find($id);
            if (!$admin) {
                throw new \Exception('管理员不存在');
            }
            
            // 不能删除超级管理员
            if ($admin->role_id == 1) {
                throw new \Exception('不能删除超级管理员');
            }
            
            // 不能删除自己
            if ($admin->id == $request->adminId) {
                throw new \Exception('不能删除自己');
            }
            
            $admin->delete();
            
            // 记录操作日志
            $this->recordOperationLog('删除', '删除管理员：' . $admin->username);
            
            Db::commit();
            return $this->success('删除成功');
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('删除管理员失败: ' . $e->getMessage());
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 修改密码
     */
    public function password(Request $request)
    {
        $data = $this->validate($request->post(), [
            'old_password' => 'require|length:6,20',
            'new_password' => 'require|length:6,20',
            'confirm_password' => 'require|confirm:new_password'
        ]);
        
        try {
            $admin = Admin::find($request->adminId);
            
            // 验证旧密码
            if (!password_verify($data['old_password'], $admin->password)) {
                throw new \Exception('原密码错误');
            }
            
            // 更新密码
            $admin->save([
                'password' => password_hash($data['new_password'], PASSWORD_DEFAULT),
                'update_time' => date('Y-m-d H:i:s')
            ]);
            
            // 记录操作日志
            $this->recordOperationLog('修改', '修改密码');
            
            return $this->success('修改成功');
        } catch (\Exception $e) {
            Log::error('修改密码失败: ' . $e->getMessage());
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 记录操作日志
     */
    protected function recordOperationLog($type, $content)
    {
        Db::name('platform_operation_log')->insert([
            'admin_id' => request()->adminId,
            'operation_type' => $type,
            'operation_content' => $content,
            'create_time' => date('Y-m-d H:i:s')
        ]);
    }
} 